/* OTA example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "esp_http_client.h"
#include "esp_https_ota.h"
#include "main.h"

static const char *TAG = "[OTA]";

#define HASH_LEN 32

#define OTA_URL_SIZE 256


#define CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP
#define CONFIG_USE_CERT_BUNDLE
#ifdef CONFIG_USE_CERT_BUNDLE
#include "esp_crt_bundle.h"
#endif

esp_err_t _http_event_handler(esp_http_client_event_t *evt)
{
    switch (evt->event_id) {
        case HTTP_EVENT_ERROR:
            ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
            break;
        case HTTP_EVENT_ON_CONNECTED:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
            break;
        case HTTP_EVENT_HEADER_SENT:
            ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
            break;
        case HTTP_EVENT_ON_HEADER:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
            break;
        case HTTP_EVENT_ON_DATA:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
            break;
        case HTTP_EVENT_ON_FINISH:
            ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
            break;
        case HTTP_EVENT_DISCONNECTED:
            ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED");
            break;
        case HTTP_EVENT_REDIRECT:
            ESP_LOGD(TAG, "HTTP_EVENT_REDIRECT");
            break;
        default:
            break;
    }
    return ESP_OK;
}

static void print_sha256(const uint8_t *image_hash, const char *label)
{
    char hash_print[HASH_LEN * 2 + 1];
    hash_print[HASH_LEN * 2] = 0;
    for (int i = 0; i < HASH_LEN; ++i) {
        sprintf(&hash_print[i * 2], "%02x", image_hash[i]);
    }
    ESP_LOGI(TAG, "%s %s", label, hash_print);
}

void get_sha256_of_partitions(void)
{
    uint8_t sha_256[HASH_LEN] = { 0 };
    esp_partition_t partition;

    // get sha256 digest for bootloader
    partition.address   = ESP_BOOTLOADER_OFFSET;
    partition.size      = ESP_PARTITION_TABLE_OFFSET;
    partition.type      = ESP_PARTITION_TYPE_APP;
    esp_partition_get_sha256(&partition, sha_256);
    print_sha256(sha_256, "SHA-256 for bootloader: ");

    // get sha256 digest for running partition
    esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256);
    print_sha256(sha_256, "SHA-256 for current firmware: ");
}


esp_err_t simple_ota_func(char *urlStr)
{
    ESP_LOGI(TAG, "Starting OTA example task");

    esp_http_client_config_t config = {
        .url = urlStr,
        .event_handler = _http_event_handler,
        .keep_alive_enable = true,

#ifdef CONFIG_USE_CERT_BUNDLE
        .crt_bundle_attach = esp_crt_bundle_attach,
#else
        // .cert_pem = (char *)server_cert_pem_start,
#endif
        .skip_cert_common_name_check = true,  //Skip server certificate CN fieldcheck
        
    };
    esp_https_ota_config_t ota_config = {
        .http_config = &config,
    };
    ESP_LOGI(TAG, "Attempting to download update from %s", config.url);
    
    esp_err_t ret = esp_https_ota(&ota_config);
    
    return ret;
}

// void simple_ota_task(void *arg)
// {
//     esp_err_t ret = simple_ota_func(ota_url);
//     if (ret == ESP_OK) {
//         ESP_LOGI(TAG, "Base board OTA Succeed, Rebooting...");
//         fflush(stdout);
//         esp_restart();
//     } else {
//         ESP_LOGE(TAG, "Base board firmware upgrade failed, err:%d", ret);
//     }
//     while (1) {
//         vTaskDelay(1000 / portTICK_PERIOD_MS);
//     }
// }

// void simple_ota(void)
// {
//     ESP_LOGI(TAG, "radar OTA init");

//     xTaskCreate(&simple_ota_task, "simple_ota_task", 8192, NULL, 6, NULL);
// }
